<template>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
      <router-link class="navbar-brand" to="/">博客系统</router-link>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav me-auto">
          <li class="nav-item">
            <router-link class="nav-link" to="/">首页</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/categories">分类</router-link>
          </li>
        </ul>
        <ul class="navbar-nav">
          <li v-if="!isLoggedIn" class="nav-item">
            <router-link class="nav-link" to="/login">登录</router-link>
          </li>
          <li v-if="!isLoggedIn" class="nav-item">
            <router-link class="nav-link" to="/register">注册</router-link>
          </li>
          <li v-if="isLoggedIn" class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
              {{ currentUser.username }}
            </a>
            <ul class="dropdown-menu">
              <li><a class="dropdown-item" href="#" @click.prevent="logout">退出登录</a></li>
            </ul>
          </li>
          <li v-if="isLoggedIn && currentUser.role === 'admin'" class="nav-item">
            <router-link class="nav-link btn btn-outline-light btn-sm" to="/admin">
              <i class="bi bi-gear"></i> 管理后台
            </router-link>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

export default {
  name: 'MainNavbar',
  setup() {
    const router = useRouter()
    const isLoggedIn = ref(false)
    const currentUser = ref({
      username: '',
      role: ''
    })

    const checkAuth = () => {
      const token = localStorage.getItem('userToken')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        isLoggedIn.value = true
        currentUser.value = JSON.parse(userInfo)
      } else {
        isLoggedIn.value = false
        currentUser.value = { username: '', role: '' }
      }
    }

    const logout = () => {
      localStorage.removeItem('userToken')
      localStorage.removeItem('userInfo')
      isLoggedIn.value = false
      currentUser.value = { username: '', role: '' }
      router.push('/')
    }

    onMounted(() => {
      checkAuth()
      
      // 监听storage变化，以便在多个标签页间同步登录状态
      window.addEventListener('storage', checkAuth)
    })

    return {
      isLoggedIn,
      currentUser,
      logout
    }
  }
}
</script>

<style scoped>
.navbar-brand {
  font-weight: bold;
}

.nav-link {
  margin: 0 5px;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}
</style>